<?php
namespace app\util;


use app\traits\EnvTrait;

class Yizun
{

    use EnvTrait;

    const ENV_TEST = 'test';
    const ENV_PROD = 'prod';

    // 应用appKey  测试
    //private $appKey = '20081';

    private $appKeyArr = [
        'test' => '20081',
        'prod' => [
            'commit' => '20125',
            'query' => '20126',
        ]
    ];
    // 公钥值 测试环境
    //private $appSecret = 'qgllgy8gogr';

    private $appSecretArr = [
        'test' => 'qgllgy8gogr',
        'prod' => [
            'commit' => 'ybt8ffaze7b',
            'query' => '3b53e6odxqh',
        ]
    ];

    // 交易成功状态
    const SUCCESS_CODE = [
        'TRADE_SUCCESS',
        'TRADE_FINISHED',
    ];

    //下单接口 测试服   这里替换掉了真实的地址
    const Test_Trade_URL = 'http://www.baidu.com';
    //下单接口 正式服  这里替换掉了真实的地址
    const Pro_Trade_URL = 'http://www.baidu.com';

    private $method;
    private $version;


    public $codeMessage = [
        '0000' => '风控检测未通过',
        '9998' => '请求超时，请稍后重试',
        '0001' => '姓名、联系电话、收获地址超限',
        '0003' => '姓名、号码归属地市超限',
        '0005' => '证件号超限',
        '0006' => '涉诈号码身份证件',
        '0007' => '异地联系电话超限',
        '0008' => '异地身份证超限',
        '0010' => '收获地址全数字',
        '0011' => '联系电话超限',
        '0013' => '一证五户超限',
        '0014' => '多地开卡',
        '0016' => '姓名中含阿拉伯数字',
        '0018' => '年龄大于100岁或小于8岁',
        '0019' => '配送地址冲突',
        '0021' => '未填写冲突地址',
        '0024' => '配送地址完全一样',
        '0025' => '恶意地址',
        '0026' => '待确认地址',
        '0027' => '30天内同一证件、同一联电、同一收获地址下单超限',
        '0028' => '配送地址省份、号码归省份、引流省份、证件归属省份不同',
        '0029' => '公安涉案',
        '0030' => '工信部涉诈涉扰',
        '0031' => '鹰眼涉诈涉扰',
        '0032' => '高龄异地单',
        '0033' => '电子围栏电话黑名单',
        '0034' => '电子围栏地市黑名单',
        '0035' => '证件开户+销户超过限制',
        '0036' => '虚假地址',
        '0037' => '证件90天内订单超过限制',
    ];

    public function __construct($method, $messageFormat, $locale, $version)
    {
        $this->method = $method;
        $this->messageFormat = $messageFormat;
        $this->locale = $locale;
        $this->version = $version;
    }

    //下单
    public function addTrade($data)
    {
        $params = [
            'appKey' => $this->getAppKey(),
            'method' => $this->method,
            'locale' => $this->locale,
            'messageFormat' => $this->messageFormat,
            'merchantNick' => $data['merchantNick'],
            'merchantId' => $data['merchantId'],
            'buyer' => $data['buyer'],
            'source' => $data['source'],
            'sourceTradeId' => $data['sourceTradeId'],
            'tradeType' => $data['tradeType'],
            'transactor' => $data['transactor'],
            'tradeAddress' => $data['tradeAddress'],
            'tradeGoods' => $data['tradeGoods'],
            'tradeExp' => $data['tradeExp'],
            'v' => $this->version,
        ];

        $params = $this->makeSign($params);
        //这里注释了真实请求
//        $result = Tools::curlPost($this->getUrl(), $params,false);
        //模拟真实请求的返回
        $result = [
            'code' => '00000000',
            'tradeId' => '234453454345435',
            'skuName' => '金卡'
        ];
        if ($result['code'] === '00000000') {
            $data = ['tradeId' => $result['tradeId'], 'skuName' => $result['skuName']];
            return ['code' => 0, 'data'=>$data];
        } else {
            return ['code' => $result['code']??1, 'message' => $result['message']??'下单失败'];
        }


    }

    //查询
    public function query($data)
    {
        $params = [
            //'appKey' => $this->appKey,
            'appKey' => $this->getAppKey('query'),
            'method' => $this->method,
            'locale' => $this->locale,
            'messageFormat' => $this->messageFormat,
            'v' => $this->version,
            'param' => $data
        ];

        $params = $this->makeSign($params, 'query');

        //$result = Tools::curlPost($this->getUrl(), $params, false);
        $result = [
            'code' =>  '00000000',
            'data' => '[{
                "logisticsCompany": "",
                "phoneNum": "",
                "tradeStatus": "01",
                "tradeId": 271788511,
                "sourceTradeId": "CDS202108221947399001",
                "merchantPid": "193872",
                "rechargeDate": "",
                "logisticsNo": "",
                "merchantId": 194502,
                "activationDate": ""
            }'
        ];
//        dump($result);die;
        if ($result['code'] === '00000000') {
            return ['code' => 0, 'data' => $result['data'] ?? [] ];
        } else {
            return ['code' => $result['code'], 'message' => $result['message']];
        }
    }

    //选号
    public function selectPhoneNum($data)
    {
        $params = [
            //'appKey' => $this->appKey,
            'appKey' => $this->getAppKey(),
            'method' => $this->method,
            'locale' => $this->locale,
            'v' => $this->version,
            'messageFormat' => $this->messageFormat,
            'goodsId' => $data['goodsId'],
            'cityCode' => $data['cityCode'],
            'provinceCode' => $data['provinceCode'],
            'amounts' => $data['amounts'],
            'searchValue' => $data['searchValue'],
        ];

//        $params = $this->makeSign($params);
        //$result = Tools::curlPost($this->getUrl(), $params, false);
        $result = [
            'code' => '0000',
            'data' => [
                            [
                                "accNbr" => "19158254348",
                                "numberId" => "92c3fccc4c0a11eca6ee2f3e1d298044"
                            ],
                            [
                                "accNbr" => "19164752148",
                                "numberId" => "903c77ea4c0a11eca3861b234c322615"
                            ],
                           
                        ]

        ];
        if ($result['code'] === '0000') {
            return ['code' => 0, 'data' => $result['data'] ??''];
        } else {
            return ['code' => $result['code'], 'message' => $result['message']];
        }

    }


    //验证号码是否被占用
    public function isOccupy($data)
    {
        $params = [
            //'appKey' => $this->appKey,
            'appKey' => $this->getAppKey(),
            'method' => $this->method,
            'locale' => $this->locale,
            'v' => $this->version,
            'messageFormat' => $this->messageFormat,
            'serialNumber' => $data['serialNumber'],
            'cityCode' => $data['cityCode'],
            'provinceCode' => $data['provinceCode'],
            'certCode' => $data['certCode'],
        ];

        $params = $this->makeSign($params);
        //$result = Tools::curlPost($this->getUrl(), $params, false);
        $result['code'] = '0000';
        if ($result['code'] === '0000') {
            return ['code' => 0];
        } else {
            return ['code' => $result['code'], 'message' => $result['message']];
        }

    }

    //验证号码是否被占用
    public function validate($data)
    {
        $params = [
            'appKey' => $this->getAppKey(),
            'method' => $this->method,
            'locale' => $this->locale,
            'v' => $this->version,
            'messageFormat' => $this->messageFormat,
            'params' => $data['params'],
            'chanId' => self::inEnvTesting() ? 20081 : 20125,
        ];

        $params = $this->makeSign($params);
        //$result = Tools::curlPost($this->getUrl(), $params, false);
        $result['code'] = '00000000';
        if (isset($result['code']) && $result['code'] === '00000000') {
            return ['code' => 0];
        } else {
            return ['code' => $result['resData'][0]['gztCode'] ?? $result['code'] ?? 1 , 'message' =>  $result['resData'][0]['gztDesc']] ?? $result['message'] ?? '';
        }

    }


    /**
     * 获取签名
     */
    function makeSign($params, $type = 'commit')
    {

        ksort($params);

        $buff = "";
        foreach ($params as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . $v;
            }
        }
        $appSecret = $this->getSecret($type);

        //$sign_str = $this->appSecret . $buff . $this->appSecret;
        $sign_str = $appSecret  . $buff . $appSecret;

        $sign_str = htmlspecialchars_decode($sign_str);
        $params['sign'] = strtoupper(sha1($sign_str));

        //var_dump($params['sign']); ;die;
        return $params;
    }

    private function getAppKey($type = 'commit')
    {
        $env = env('APP_ENV');
        return self::inEnvTesting() ? $this->appKeyArr[$env] : $this->appKeyArr[$env][$type];
    }

    private function getSecret($type = 'commit')
    {
        $env = env('APP_ENV');
        return self::inEnvTesting() ? $this->appSecretArr[$env] : $this->appSecretArr[$env][$type];
    }

    private function getUrl()
    {
        return self::inEnvTesting() ? self::Test_Trade_URL : self::Pro_Trade_URL;
    }

    //查询
    public function riskCheck($data)
    {
        $params = [
            //'appKey' => $this->appKey,
            'appKey' => $this->getAppKey('commit'),
            'method' => $this->method,
            'locale' => $this->locale,
            'messageFormat' => $this->messageFormat,
            'v' => $this->version,
            'params' => $data,
            'chanId' => self::inEnvTesting() ? 20081 : 20125,
        ];

        $params = $this->makeSign($params, 'commit');

        $result = Tools::curlPost($this->getUrl(), $params, false);
//        dump($result);die;
        if ($result['code'] === '00000000') {
            return ['code' => 0, 'data' => $result['data'] ?? [] ];
        } else {
            return ['code' => $result['code'], 'message' => $this->codeMessage[$result['upCode']] ?? '未知错误，下单失败！'];
        }
    }
}
